[BITS 16]
[ORG 0x7C00]

	%include "include/defines.inc"
	
	cli
	xor	ax,	ax
	mov	ds,	ax
	mov	es,	ax
	mov	ax,	0x9000
	mov	ss,	ax
	mov	sp,	0xFFFF
	sti

	mov	[disknum],	dl
	
	mov	si,	welcome	; string pointer
	call	printString	; print string
	
reset:	xor	ah,	ah	; function 0
	mov	dl,	[disknum]	; disk number
	int	0x13		; reset disk
	jc	reset		; try again if failed

	
	mov	si,	loading	; string pointer
	call	printString	; print string
	
	cmp	byte	[part_1],	0x80
	je .p1
	cmp	byte	[part_2],	0x80
	je .p2
	cmp	byte	[part_3],	0x80
	je .p3
	cmp	byte	[part_4],	0x80
	je .p4
	
	.p1:
	mov	cl,	[part_1+start_sector]
	mov	ch,	[part_1+start_cylinder]
	mov	dh,	[part_1+start_head]
	jmp	loadVBR
	
	.p2:
	mov	cl,	[part_2+start_sector]
	mov	ch,	[part_2+start_cylinder]
	mov	dh,	[part_2+start_head]
	jmp	loadVBR

	.p3:
	mov	cl,	[part_3+start_sector]
	mov	ch,	[part_3+start_cylinder]
	mov	dh,	[part_3+start_head]
	jmp	loadVBR

	.p4:
	mov	cl,	[part_4+start_sector]
	mov	ch,	[part_4+start_cylinder]
	mov	dh,	[part_4+start_head]
	jmp	loadVBR

loadVBR:
;	mov	eax,	0x7C00
;	mov	[eax],	byte 0xC3
;	jmp	dword	far [eax]

	mov	ax,	0x2000
	mov	es,	ax
	mov	dl,	[disknum]	; disk number
	mov	ah,	0x02	; read
	mov	al,	0x01	; 256 sectors * 512 bytes (131972 bytes / 128k)
	mov	bx,	VBR_SEG
	mov	es,	bx	; ... buffer segment
	mov	bx,	VBR_ADDR	; buffer start

	int	0x13		; read sector
	jc	loadVBR	; read again if failed


	mov	si,	booting	; string pointer
	call	printString	; print string

	mov	dl,	[disknum]
	
;	mov	ax,	0x2000
	mov	ax,	0x0000
	mov	ds,	ax	;	...
	mov	es,	ax
	mov	ss,	ax
	
;	jmp	0x2000:0x1000	; jump to kernel
	jmp	0x0500

	welcome	db	" # AOS Boot Loader",13,10,0
	loading	db	" # Loading VBR from hard disk...",13,10,0
	booting	db	" # Starting bootloader...",13,10,0

	disknum	db	0	; disk number
	
%include "include/io.inc"

	times	440-($-$$) db 0	; fill to 440 bytes
	disk_signature	dd	0
	dw	0
	part_1: 
    istruc  PartitionRecord
	at boot,	db	0
	at start_head,	db	0
	at start_sector,	db	2
	at start_cylinder,	db	0
	at part_type,	db	0xDA
	at end_head,	db	0
	at end_sector,	db	0
	at end_cylinder,	db	0
	at start_lba,	dd	0
	at secnum,	dd	0
    iend
   	part_2: 
    istruc  PartitionRecord
	at boot,	db	0
	at start_head,	db	0
	at start_sector,	db	0
	at start_cylinder,	db	0
	at part_type,	db	0xDA
	at end_head,	db	0
	at end_sector,	db	0
	at end_cylinder,	db	0
	at start_lba,	dd	0
	at secnum,	dd	0
    iend
	part_3: 
    istruc  PartitionRecord
	at boot,	db	0
	at start_head,	db	0
	at start_sector,	db	0
	at start_cylinder,	db	0
	at part_type,	db	0xDA
	at end_head,	db	0
	at end_sector,	db	0
	at end_cylinder,	db	0
	at start_lba,	dd	0
	at secnum,	dd	0
    iend
	part_4: 
    istruc  PartitionRecord
	at boot,	db	0
	at start_head,	db	0
	at start_sector,	db	0
	at start_cylinder,	db	0
	at part_type,	db	0xDA
	at end_head,	db	0
	at end_sector,	db	0
	at end_cylinder,	db	0
	at start_lba,	dd	0
	at secnum,	dd	0
    iend
	dw	0xAA55		; MBR/VBR signature
